package com.zhouxiaoxuan13.gateway.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 网关管理控制器
 * 提供网关状态监控和管理功能
 */
@Slf4j
@RestController
@RequestMapping("/gateway")
public class GatewayController {

    @Autowired
    private RouteLocator routeLocator;

    /**
     * 获取网关健康状态
     */
    @GetMapping("/health")
    public Mono<ResponseEntity<Map<String, Object>>> health() {
        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("message", "网关服务正常");
        response.put("timestamp", System.currentTimeMillis());
        response.put("version", "1.0.0");
        response.put("features", List.of(
                "负载均衡",
                "链路跟踪",
                "CORS支持",
                "服务发现"
        ));

        return Mono.just(ResponseEntity.ok(response));
    }

    /**
     * 获取所有路由信息
     */
    @GetMapping("/routes")
    public Mono<ResponseEntity<Map<String, Object>>> getRoutes() {
        return routeLocator.getRoutes()
                .collectList()
                .map(routes -> {
                    List<Map<String, Object>> routeInfos = routes.stream()
                            .map(this::convertRouteToMap)
                            .collect(Collectors.toList());

                    Map<String, Object> response = new HashMap<>();
                    response.put("code", 200);
                    response.put("message", "获取路由信息成功");
                    response.put("data", Map.of(
                            "total", routeInfos.size(),
                            "routes", routeInfos
                    ));

                    return ResponseEntity.ok(response);
                });
    }

    /**
     * 转换Route对象为Map
     */
    private Map<String, Object> convertRouteToMap(Route route) {
        Map<String, Object> routeMap = new HashMap<>();
        routeMap.put("id", route.getId());
        routeMap.put("uri", route.getUri().toString());
        routeMap.put("order", route.getOrder());

        // 处理predicates
        try {
            routeMap.put("predicates", route.getPredicate() != null ?
                    List.of(route.getPredicate().toString()) : List.of());
        } catch (Exception e) {
            routeMap.put("predicates", List.of("N/A"));
        }

        // 处理filters
        try {
            routeMap.put("filters", route.getFilters().stream()
                    .map(filter -> filter.getClass().getSimpleName())
                    .collect(Collectors.toList()));
        } catch (Exception e) {
            routeMap.put("filters", List.of("N/A"));
        }

        routeMap.put("metadata", route.getMetadata());
        return routeMap;
    }
}
